package io.github.iogogogo.web.acpect;

import io.github.iogogogo.commons.util.DateTimeUtils;
import io.github.iogogogo.web.handler.ServletContextHandler;
import io.github.iogogogo.web.util.IpUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;

/**
 * Created by tao.zeng on 2024/11/17.
 */
@Data
@Slf4j
@Aspect
public class HttpLogAspect {

    @Value("${spring.application.name:unknown}")
    private String appName;

    private ThreadLocal<Long> startTime = ThreadLocal.withInitial(DateTimeUtils::now);

    @Pointcut("execution(public * *..api.*Api*.*(..))" +
            " || execution(public * *..controller.*Controller*.*(..))" +
            " || execution(public * *..rpc.*Rpc*.*(..))" +
            " || execution(public * io.github.iogogogo.web.handler.GlobalExceptionHandler.*(..))")
    public void httpLog() {
    }

    @Before("httpLog()")
    public void doBefore() throws Throwable {
        startTime.set(DateTimeUtils.now());
    }

    @AfterReturning(returning = "ret", pointcut = "httpLog()")
    public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {

        try {
            long endTime = DateTimeUtils.now();
            HttpServletRequest request = ServletContextHandler.getRequest();

            String clz = joinPoint.getSignature().getDeclaringTypeName();
            String method = joinPoint.getSignature().getName();
            String url = request.getRequestURL().toString();
            long duration = endTime - startTime.get();
            String remoteIp = IpUtils.getRemoteHost(request);

            log.info("appName: {}, method: {}#{}, url: {}, ip: {}, duration: {}, ret:{} ", appName, clz, method, url, remoteIp, duration, ret);

        } finally {
            startTime.remove();
        }
    }
}
